//
//  HJoauthVCViewController.swift
//  HJWeiBo
//
//  Created by 黄珏 on 15/10/28.
//  Copyright © 2015年 黄珏. All rights reserved.
//

import UIKit
import SVProgressHUD

class HJoauthVCViewController: UIViewController,UIWebViewDelegate {

    override func loadView() {
        view = webView
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "退出", style: UIBarButtonItemStyle.Plain, target: self, action: "dismissVC")
        webView.loadRequest(NSURLRequest(URL: NetworkTools.shareInstance.oauthUrl()))
    }
    /**
    dismiss当前视图
    */
    func dismissVC() {
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }

    //MARK: - 代理方法
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.showWithStatus("老子帮你加载中,急毛", maskType: SVProgressHUDMaskType.Gradient)
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    /*
    登录成功,加载:https://api.weibo.com/oauth2/authorize
    点击取消授权,加载: http://gz.itcast.cn/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330
    
    点击授权,加载: http://gz.itcast.cn/?code=9a854bfa76a725689c7ff59961b0cc04
    */
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        ///request.URL 返回的是NSURL类型的数据
        ///request.URL?.absoluteString 返回的是String类型的数据
        let urlString = request.URL!.absoluteString
        print("fuck = \(request.URL)")
        print("urlString = \(urlString)")
        if !urlString.hasPrefix(NetworkTools.shareInstance.redirect_uri) {
            return true
        }
//        前缀是百度的往下走
        let code: String?
        if let query = request.URL?.query {
            let codeString = "code="
            let nsQuery = query as NSString
            if nsQuery.hasPrefix(codeString) {
//                点击授权
                code = nsQuery.substringFromIndex(codeString.characters.count)
                print(code)
                loadAccessToken(code!)
                return false
            } else {
//                点击取消
                dismissVC()
                return false
            }
        }
        
        return true
    }
    

    ///加载AccessToken
    func loadAccessToken(code: String) {
        NetworkTools.shareInstance.loadAccessToken(code) { (result, error) -> () in
//            这个闭包里的内容是否执行（在哪执行）要看loadAccessToken方法是否调用（在哪调用）
            if error != nil || result == nil {
                self.netError("授权失败")
                return
            }
            print("result = \(result)")
            // 字典转模型
            let account = HJUserAccount(dict: result!)
            // 保存到沙盒 : 保存基本用户数据 access_token，expires_in，uid
            account.saveAccount()
            
            // 加载用户数据: 加载用户个性数据用户名，头像。。。
            account.loadUserInfo({ (error) -> () in
                if error != nil {
                    self.netError("加载用户数据出错。。。")
                    return
                }

                self.dismissVC()
//                跳转控制器 加载欢迎界面
                (UIApplication.sharedApplication().delegate as! AppDelegate).switchRootController(false)
            })
        }

    }
    func netError(message: String) {
        SVProgressHUD.showErrorWithStatus(message)
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
            self.dismissVC()
        })
    }
    //MARK: - 懒加载
    lazy var webView = UIWebView()

}
